import axios from 'axios'
import api from '@/config/api.js'

const http = axios.create({
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
function initToken() {
  if (sessionStorage.getItem('token')) {
    http.defaults.headers.AUTHORIZATION = 'Bearer ' + sessionStorage.getItem('token')
  }
}
http.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401: // token 失效
          // window.location.href = '/'
          break
      }
    }
    return Promise.reject(error)
  }
)
function get(path, params, callback) {
  initToken()
  http
    .get(api[path]['url'], {
      params: params
    })
    .then((response) => {
      callback(response.data)
    })
    .catch(function (err) {
      if (err.response) {
        callback(err.response.data)
      }
    })
}
function getUrl(path, params, callback) {
  initToken()
  let url = api[path]['url']
  if (params.id) {
    url = url + params.id + '/'
  }
  http
    .get(url, { params: params.params })
    .then((response) => {
      callback(response.data)
    })
    .catch(function (err) {
      if (err.response) {
        callback(err.response.data)
      }
    })
}
function post(path, params, callback) {
  initToken()
  const url = api[path]['url']
  http
    .post(url, params)
    .then((response) => {
      callback(response.data)
    })
    .catch(function (err) {
      if (err.response) {
        callback(err.response.data)
      }
    })
}
export default {
  get,
  post,
  getUrl
}
